<template>
  <!-- <el-dialog
    title="Banner"
    :visible.sync="goNewbanner"
    width="30%"
    @open="openDialog"
  > -->
  <div class="addBanner flex">
    <el-row :gutter="24">
      <el-col :span="8"> {{ operationTitle }}banner</el-col>
      <el-col :span="16" style="text-align: right">
        <el-button
          type="primary"
          icon="el-icon-refresh"
          size="mini"
          @click="$router.go(0)"
          >刷新
        </el-button>
        <el-button
          type="primary"
          icon="el-icon-refresh"
          size="mini"
          @click="$router.go(-1)"
          >返回
        </el-button>
      </el-col>
    </el-row>
    <el-card class="box-card">
      <div class="text item">
        <el-form
          ref="addbannerForm"
          :model="addBanner"
          :rules="rules"
          size="medium"
          :label-position="isSmall ? 'top' : 'right'"
          label-width="130px"
        >
          <el-form-item label="Banner名称" prop="bannerName">
            <el-input
              v-model="addBanner.bannerName"
              placeholder="请填入banner名称"
              clearable
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="URL地址" prop="urlType">
            <el-select
              v-model="addBanner.urlType"
              filterable
              placeholder="请选择URL地址"
              clearable
              :style="{ width: '100%' }"
            >
              <el-option
                v-for="(item, index) in chooseAddress"
                :key="index"
                :label="item.dictLabel"
                :value="Number(item.dictValue)"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="外链地址"
            prop="outLineUrl"
            v-show="addBanner.urlType == '0'"
          >
            <el-input
              v-model="addBanner.outLineUrl"
              placeholder="请输入外链地址"
              clearable
              :style="{ width: '100%' }"
            >
            </el-input>
          </el-form-item>
          <el-form-item
            label="内链地址"
            prop="innerLineUrl"
            v-show="addBanner.urlType == '1'"
          >
            <el-input
              v-model="addBanner.innerLineUrl"
              placeholder="请输入内链地址"
              clearable
            >
            </el-input>
          </el-form-item>
          <el-form-item label="开始时间：" prop="showBeginTime">
            <el-date-picker
              v-model="addBanner.showBeginTime"
              type="datetime"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="请选择开始时间"
              :picker-options="startDatePicker"
              :style="{ width: '100%' }"
              @change="changeStartValue"
              @focus="focusStartVlaue"
              clearable
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间：" prop="showEndTime">
            <el-date-picker
              v-model="addBanner.showEndTime"
              type="datetime"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              placeholder="请选择结束时间"
              :picker-options="endDatePicker"
              :style="{ width: '100%' }"
              @change="changeEndValue"
              clearable
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="显示顺序" prop="orderNo">
            <el-input
              v-model="addBanner.orderNo"
              placeholder="请输入显示顺序"
              clearable
              :style="{ width: '100%' }"
              @input="inputValue"
            >
            </el-input>
          </el-form-item>
          <el-form-item label="上传" prop="bannerUrl">
            <div class="imgBanner">
              <el-image :src="addBanner.bannerUrl" alt="" v-loading="isUploading" element-loading-text="图片上传中...">
                <div slot="error" class="image-slot">
                  <span>请在此上传图片</span>
                  <!-- <i class="el-icon-plus"  v-else></i> -->
                </div>
              </el-image>
            </div>
            <el-row>
              <el-col :span="12">
                <el-upload
                  ref="imgUrl"
                  name="multipartFile"
                  :headers="headers"
                  :disabled="isUploading"
                  :action="imgUrlAction"
                  accept=".jpg,.jpeg,.png"
                  :limit="1"
                  :file-list="fileList"
                  :on-success="onSuccess"
                  :before-upload="beforeAvatarUpload"
                  :on-progress="handleUploadProgress"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload></el-col
              >
            </el-row>
            <!-- 预览弹框 -->
            <el-dialog :visible.sync="dialogVisible" style="width: 500px">
              <img width="100%" :src="addBanner.bannerUrl" alt="" />
            </el-dialog>
          </el-form-item>
          <el-form-item>
            <div class="el-upload__tip">
              请上传XXX*XXXX像素XXXX格式的图片，展示效果最佳，文件大小不超过XXXXX
            </div>
          </el-form-item>
          <el-form-item
            size="large"
            class="lastConfirm flex"
            :style="{ width: '100%' }"
          >
            <el-button type="primary" :loading="loading" @click="submitForm"
              >保存</el-button
            >
            <el-button type="primary" class="lastbtn" @click="imgPreview"
              >预览</el-button
            >
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>

  <!-- </el-dialog> -->
</template>
<script>
import { getToken } from "@/utils/auth";
import {
  getInforBanner,
  AddBanner,
  UpdateBanner,
} from "@/api/gwoper/bannerList";

export default {
  name: "addBanner",
  // props: {
  //   goNewbannerFu: Boolean,
  //   idFu: [Number, String],
  // },
  data() {
    let validateNum = (rule, value, callback) => {
      const reg = /(ht|f)tp(s?)\:\/\/[0-9a-zA-Z]([-.\w]*[0-9a-zA-Z])*(:(0-9)*)*(\/?)([a-zA-Z0-9\-\.\?\,\'\/\\\+&amp;%\$#_]*)/
      if(this.addBanner.urlType == 0){
        if(rule.field == "outLineUrl"){
          if(!this.addBanner.outLineUrl){
            callback(new Error('请输入外链地址'));
          } else if (!reg.test(value)) {
            callback(new Error('请输入正确的外链地址格式（http、https、ftp、ftps）'));
          } else {
            callback();
          }
        }else{
          callback();
        }
      }else{
        if(rule.field == "innerLineUrl"){
          if(!this.addBanner.innerLineUrl){
            callback(new Error('请输入内链地址'));
          }else {
            callback();
          }
        }else{
          callback();
        }
      }
      // if(this.addBanner.urlType == 0){
      //   if (!this.addBanner.outLineUrl) {
      //     callback(new Error());
      //   } else {
      //     callback();
      //   }
      // }else if(this.addBanner.urlType == 1){
      //   if (!this.addBanner.innerLineUrl) {
      //     callback(new Error());
      //   } else {
      //     callback();
      //   }
      // }
    };

    return {
      isUploading: false,// 图片上传蒙层
      loading: false,
      // goNewbanner: this.goNewbannerFu,
      // id: this.idFu,
      addBanner: {
        // id: this.idFu,
        id: null,
        onSell: null,
        bannerName: null,
        bannerUrl: null,
        orderNo: null,
        urlType: null,
        innerLineUrl: null,
        outLineUrl: null,
        showBeginTime: null,
        showEndTime: null,
      },
      // 时间选择
      startDatePicker: this.processDateStart(),
      endDatePicker: this.processDateEnd(),
      chooseAddress: [],
      // 表单验证
      rules: {
        bannerName: [
          {
            required: true,
            message: "请输入banner名称",
            trigger: "blur",
          },
        ],
        urlType: [
          {
            required: true,
            message: "请至少选择一个url地址",
            trigger: "change",
          },
        ],
        outLineUrl: [
          {
            required: true,
            validator: validateNum,
            trigger: "blur",
          },
        ],
        innerLineUrl: [
          {
            required: true,
            validator: validateNum,
            trigger: "blur",
          },
        ],
        showBeginTime: [
          {
            required: true,
            message: "日期范围不能为空",
            trigger: "change",
          },
        ],
        showEndTime: [
          {
            required: true,
            message: "日期范围不能为空",
            trigger: "change",
          },
        ],
        orderNo: [
          {
            required: true,
            message: "请输入排序值",
            trigger: "blur",
          },
        ],
        bannerUrl: [
          {
            required: true,
            message: "请上传图片",
            trigger: "blur",
          },
        ],
      },
      disabled: false,
      isSmall: false, // 屏幕大小变化改变样式状态
      screenWidth: document.body.clientWidth, // 屏幕宽度
      // 预览banner
      previewBanner: false,
      // 图片上传接口
      imgUrlAction:
        process.env.VUE_APP_BASE_API + "/operation-center/banner/upload",
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      // 上传的图片
      dialogImageUrl: "",
      dialogVisible: false,
      picList: [],
      fileList: [],
    };
  },
  created() {
    this.getDicts("gwoper_banner_adr").then(response => {
      this.chooseAddress = response.data;
    });
    this.addBanner.id = this.$route.query.id ? this.$route.query.id : null;
    // this.addBanner.id = this.idFu ? this.idFu : null;
    if (this.addBanner.id) {
      this.getInfo();
      this.operationTitle = "修改";
    } else {
      this.operationTitle = "新增";
    }
  },
  mounted() {
    console.log("mounted");
    const that = this;
    window.addEventListener("resize", function () {
      return (() => {
        window.screenWidth = document.body.clientWidth;
        that.screenWidth = window.screenWidth;
      })();
    });
    if (that._isMobile()) {
      // 手机端
      this.isSmall = true;
    } else {
      // pc端
      this.isSmall = false;
    }
  },
  watch: {
    '$route.query'(val){
    this.addBanner.id = val.id==undefined ? null : val.id;
    if (this.addBanner.id) {
      this.getInfo();
      this.operationTitle = "修改";
    } else {
      this.operationTitle = "新增";
      this.resetForm()
    }
  },
    // goNewbannerFu(val) {
    //   this.goNewbanner = val;
    // },
    // idFu(val) {
    //   this.addBanner.id = val;
    // },
    screenWidth(val) {
      // console.log(this.addBanner.id);
      // console.log(val);
      this.screenWidth = val;
      if (this.screenWidth < 768) {
        this.isSmall = true;
      } else {
        this.isSmall = false;
      }
    },
  },
  methods: {
    // openDialog() {
    //   if (this.addBanner.id) {
    //     this.getInfo();
    //     this.operationTitle = "修改";
    //   } else {
    //     this.operationTitle = "新增";
    //   }
    // },
    _isMobile() {
      let flag = navigator.userAgent.match(
        /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
      );
      return flag;
    },
    // 获取详情
    getInfo() {
      getInforBanner(this.addBanner.id)
        .then((res) => {
          // console.log(res, "11");
          this.addBanner.onSell = res.data.onSell;
          // console.log(this.addBanner.onSell, "onsell");
          if (res.code != 200) {
            return this.msgError(res.msg);
          }
          this.addBanner = res.data;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    // 输入排序值
    inputValue(value) {
      this.addBanner.orderNo = value.replace(/[^\d]/g, "");
    },
    // 时间选择
    changeStartValue(value) {
      if (this.addBanner.showEndTime) {
        if (
          new Date(value).getTime() >=
          new Date(this.addBanner.showEndTime).getTime()
        ) {
          this.addBanner.showBeginTime = null;
          this.msgInfo("开始时间需小于结束时间");
        }
      }
    },
    // 修改时候点击开始时间 后面的结束时间清空
    focusStartVlaue() {
      if (this.addBanner.id) {
        this.addBanner.showEndTime = null;
      }
    },
    changeEndValue(value) {
      console.log(value);
      console.log(new Date(value).getTime());
      if (
        new Date(value).getTime() <=
        new Date(this.addBanner.showBeginTime).getTime()
      ) {
        this.addBanner.showEndTime = null;
        this.msgInfo("结束时间需大于开始时间");
      }
    },
    /* 结束时间不能大于开始时间 */
    // processDate() {
    //   const self = this;
    //   return {
    //     disabledDate(time) {
    //       // 如果开始时间不为空，则结束时间大于开始时间
    //       if (self.addBanner.showBeginTime) {
    //         return (
    //           new Date(self.addBanner.showBeginTime).getTime() > time.getTime()
    //         );
    //       } else {
    //         // 开始时间不选时，结束时间最大值小于等于当天日期
    //         return time.getTime() > Date.now();
    //       }
    //     },
    //   };
    // },

    // 开始时间不能大于结束时间
    processDateStart() {
      const that = this;
      return {
        disabledDate(time) {
          // 如果结束时间不为空，则开始时间小于结束时间
          if (that.addBanner.showEndTime) {
            return (
              new Date(that.addBanner.showEndTime).getTime() < time.getTime()
            );
          }
        },
      };
    },
    /* 结束时间不能小于开始时间 */
    processDateEnd() {
      const that = this;
      return {
        disabledDate(time) {
          // 如果开始时间不为空，则结束时间大于开始时间
          if (that.addBanner.showBeginTime) {
            return (
              new Date(that.addBanner.showBeginTime).getTime() > time.getTime()
            );
          }
        },
      };
    },
    // 关闭
    // closeDialog() {
    //   this.goNewbanner = false;
    //   this.$emit("closeAddBanner", false);
    // },
    // 保存
    submitForm() {
      console.log(this.addBanner)
      // 防止重复提交
      this.loading = true;
      this.$refs["addbannerForm"].validate((valid) => {
        if (!valid) return this.loading = false;
        // TODO 提交表单
        // console.log(this.addBanner);
        console.log()
        if(this.addBanner.urlType==0){
          this.addBanner.innerLineUrl = ""
        }else{
          this.addBanner.outLineUrl = ""
        }

        if (this.addBanner.id == null) {
          this.addBanner.onSell = 2;
          AddBanner(this.addBanner).then((res) => {
            console.log(res, "11");
            if (res.code != 200) {
              this.loading = false
              return this.msgError(res.msg);
            }
            this.msgSuccess(res.msg);
            this.resetForm();
            this.emptyUpload();
            // this.closeDialog();
            this.loading = false
            this.$router.push("/gwoper/banner");
          }).catch(err=>{
            console.log(err)
            return this.loading = false
          });
        } else {
          if (this.addBanner.onSell == 3) {
            this.addBanner.onSell = 2;
          }
          UpdateBanner(this.addBanner).then((res) => {
            // console.log(res, "222");
            if (res.code != 200) {
              this.loading = false
              return this.msgError(res.msg);
            }
            this.msgSuccess(res.msg);
            this.resetForm();
            // this.closeDialog();
            this.loading = false
            this.$router.push("/gwoper/banner");
          }).catch(err=>{
            console.log(err)
            return this.loading = false
          });
        }
      });
    },
    // 图片上传成功时的钩子
    onSuccess(res, file) {
      // console.log(res, "111");
      this.addBanner.bannerUrl = res;
      this.fileList[0] = {
        name: file.name,
        url: res,
      };
      this.$refs["imgUrl"].clearFiles(); //上传成功之后清除历史记录
      this.isUploading = false
    },
    // 图片上传成功前钩子
    beforeAvatarUpload(file) {
      // console.log(file, "22");
      const isJPG = file.type === "image/jpg";
      const isPng = file.type === "image/png";
      const isJPEG = file.type === "image/jpeg";
      const isLt20M = file.size / 1024 / 1024 < 30;
      if (file == null) {
        if (!isJPG && !isPng && !isJPEG) {
          this.$message.info("上传图片只能是 JPG,JPEG或png 格式!");
        }
        if (!isLt20M) {
          this.$message.info("上传图片大小不能超过 20MB!");
        }
        return (isJPG || isPng || isJPEG) && isLt20M;
      }
    },
    // 文件上传中处理
    handleUploadProgress(event, file, fileList) {
      this.isUploading = true;
    },
    // 预览
    imgPreview() {
      // console.log(11);
      this.addBanner.bannerUrl = this.addBanner.bannerUrl;
      this.dialogVisible = true;
    },
    /**
     * 清空上传组件
     */
    emptyUpload() {
      // const mainImg = this.$refs.upload;
      // if (mainImg) {
      //   if (mainImg.length) {
      //     mainImg.forEach((item) => {
      //       item.clearFiles();
      //     });
      //   } else {
      // this.$refs.imgUrl.clearFiles();
      //   }
      // }
    },
    // 重置表单
    resetForm() {
      // console.log(111);
      this.$refs["addbannerForm"].resetFields();
    },
  },
};
</script>
<style lang="scss"  >
@import "@/assets/styles/card.scss";

.addBanner {
  flex-direction: column;
  padding: 20px;

  .el-textarea__inner {
    min-height: 200px !important;
  }
  .el-form {
    max-width: 800px;
    margin: 0 auto;
  }
  .el-form-item__label {
    width: 130px !important;
  }
}
.el-upload__tip {
  line-height: 1.2;
}
/* 图片上传 */
.imgEdit img {
  width: 280px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.el-upload--picture-card,
.el-upload-list--picture-card .el-upload-list__item {
  width: 250px !important;
  height: 120px !important;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

// 预览
.el-carousel__item h3 {
  color: #475669;
  font-size: 14px;
  opacity: 0.75;
  line-height: 150px;
  margin: 0;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
  background-color: #d3dce6;
}

.el-image {
  position: relative;
  width: 100%;
  min-height: 150px;
  border: 1px solid #dcdfe6;

  .image-slot {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);

    // .el-icon-plus:before {
    //   font-size: 50px;
    //   color: #dcdfe6;
    // }
  }
}
.el-dialog {
  width: 500px;
}
</style>
